import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

/**
 * 
 * Sender thread which polls the buffer for packets that need
 * to be sent out
 *
 */
public class MDRRSender extends Thread {
	private MDRRBuffer buffer;
	private InetAddress receiverAddr;
	private DatagramSocket socket;

	public MDRRSender(MDRRBuffer buffer, String receiverIP) throws Exception {
		this.buffer = buffer;
		this.receiverAddr = InetAddress.getByName(receiverIP);
		socket = new DatagramSocket();
	}
	
	private void sendPacket(DatagramPacket packet, int receiverPort)
	{
		try 
		{
			// change destination of packet (do forwarding)
			packet.setAddress(receiverAddr);
			packet.setPort(receiverPort);
			//TODO: maintain departure stats
	
			socket.send(packet);
			System.out.println("Sending to port number "+packet.getPort()+"...");
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
	
	public void run()
	{
		while(true)
		{
			DatagramPacket packet = null;
			// if buffer is non empty get first packet (without removing it)
			if (buffer.hasPackets())
			{
				packet = buffer.removePacket();
				//packet will be non-null only if there was an eligible packet
				if(packet != null)
				{
		            byte[] data = packet.getData();
		            ByteBuffer byteBuffer = ByteBuffer.wrap(data);
		            int seq = byteBuffer.getInt();
		            int receiverPort = byteBuffer.getInt(); 
					sendPacket(packet, receiverPort);
				}
			}
			else
			{
				// there are no packets in buffer to send. Wait for one to arrive to buffer.
				try
				{
					synchronized (buffer)
					{
						buffer.wait();
					}
				} 
				catch (InterruptedException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}
